package com.zmn.mcc.permit.mysql.boot.autoconfigure;

import com.zmn.mcc.permit.mysql.ZmnDPermitInterceptor;
import com.zmn.mcc.permit.mysql.parsing.ZmnDPermitSqlParsing;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * 启动类：Spring自动装配
 * 动态注入SQL拦截器
 *
 * @author duanzuocai
 * @version v1.0
 * @since 2020/7/7 10:36
 */
@Configuration
@AutoConfigureAfter({MybatisAutoConfiguration.class})
@ComponentScan(basePackages = "com.zmn.mcc.permit.mysql")
public class DPermitMybatisAutoConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(DPermitMybatisAutoConfiguration.class);

    public DPermitMybatisAutoConfiguration(ObjectProvider<SqlSessionFactory[]> sqlSessionFactories, ZmnDPermitSqlParsing zmnPermitDataSqlParsing) {
        logger.info("[zmn] SQL拦截 启动配置");

        SqlSessionFactory[] factories = sqlSessionFactories.getIfAvailable();

        if (factories != null) {
            ZmnDPermitInterceptor plugin = new ZmnDPermitInterceptor(zmnPermitDataSqlParsing);

            for (SqlSessionFactory factory : factories) {
                factory.getConfiguration().addInterceptor(plugin);
                logger.info("[zmn] SQL拦截 注入拦截器：ZmnDPermitInterceptor");
            }
        }
    }

}
